package com.heima.comment.service.impl;

import com.heima.aliyun.scan.GreenScan;
import com.heima.aliyun.scan.ScanResult;
import com.heima.comment.service.CommentRepayService;
import com.heima.common.exception.CustException;
import com.heima.model.comment.dto.CommentRepayDTO;
import com.heima.model.comment.dto.CommentRepayLikeDTO;
import com.heima.model.comment.dto.CommentRepaySaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vos.ApCommentRepayVO;
import com.heima.model.comment.vos.ApCommentVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Slf4j
public class CommentRepayServiceImpl implements CommentRepayService {
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    GreenScan greenScan;

    /**
     * 查看更多回复内容
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDTO dto) {
        //1. 校验参数
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST, "数据不存在");
        }
        //评论id不能为空  size为null 或 0 设置为10  最小日期为空 设置为当前
        if (dto.getCommentId() == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "id不能为空");
        }
        if (dto.getSize() == null || dto.getSize() == 0) {
            Integer size = 10;
            dto.setSize(size);
        }
        if (dto.getMinDate() == null) {
            dto.setMinDate(new Date());
        }
        //2. 条件查询评论回复信息
        //条件:  commentId = 评论id and createdTime 小于 minDate  创建时间 降序  limit size
        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId()).and("createdTime").lt(dto.getMinDate()));
        query.limit(dto.getSize());//截取
        Sort sort = Sort.by(Sort.Direction.DESC, "createdTime");//时间降序
        query.with(sort);// 排序
        //查询
        List<ApCommentRepayVO> repayList = mongoTemplate.find(query, ApCommentRepayVO.class);
        //3. 检查是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            //3.1 如果未登录直接 返回评论回复列表
            return ResponseResult.okResult(repayList);
        }
        //3.2 如果登录，需要判断哪些回复点过赞
        //思路:
        //基于当前列表 回复id集合  及  登录人id 查询回复点赞列表
        Query authorId = Query.query(Criteria.where("authorId").is(user.getId()));
        //获得登录id点赞的数据
        List<ApCommentRepayLike> apCommentRepayLikes = mongoTemplate.find(authorId, ApCommentRepayLike.class);
        List<String> list = new ArrayList<String>();
        for (ApCommentRepayLike apCommentRepayLike : apCommentRepayLikes) {
            String commentId = apCommentRepayLike.getCommentRepayId();
            list.add(commentId);
        }
        //遍历 当前回复列表，将每一个回复信息 封装成 vo
        //判断当前回复id 在点赞信息中是否存在，如果存在 operation设置为0 不存在不做处理
        for (ApCommentRepayVO repayVO : repayList) {
            for (String commentId : list) {
                if (repayVO.getId().equals(commentId)) {
                    //如果当前评论id在点赞记录中存在  设置operation字段为0
                    repayVO.setOperation((short) 0);
                }
            }
        }
        //封装返回结果
        return ResponseResult.okResult(repayList);
    }

    /**
     * 保存回复
     *
     * @return
     */
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDTO dto) {
        //1. 参数校验:
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "数据不能为空");
        }
        //是否登录  评论id是否为空  内容是否为空  内容是否大于140个字符
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //回复内容安全校验
        //困难：阿里云内容检查，有问题替换为**
        String newContent = aliyunTextScan(dto.getContent());
        //2. 根据评论id查询评论信息  检查是否存在
        Query query = Query.query(Criteria.where("id").is(dto.getCommentId()));
        ApComment apComment = mongoTemplate.findOne(query, ApComment.class);
        if (apComment == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "评论信息不存在，无法回复");
        }
        //3. 保存评论回复信息
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(user.getId());
        apCommentRepay.setAuthorName(user.getName());
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setContent(newContent);
        apCommentRepay.setLikes(0);
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setUpdatedTime(new Date());
        //执行保存
        mongoTemplate.insert(apCommentRepay);
        //4. 修改评论信息中回复数量 + 1
        Update update = new Update();
        Integer reply = apComment.getReply();
        reply += 1;
        update.set("reply", reply).set("updatedTime", new Date());
        mongoTemplate.updateFirst(query, update, ApComment.class);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 阿里云审核敏感词
     *
     * @param content
     * @return
     */
    public String aliyunTextScan(String content) {
        try {
            ScanResult scanResult = greenScan.greenTextScan(content);
            String newContent = scanResult.getFilteredContent();
            if (StringUtils.isNotBlank(newContent)) {
                //过滤后的字符
                return scanResult.getFilteredContent();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content;
    }

    /**
     * 点赞回复的评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDTO dto) {
        //1. 校验参数
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "数据不能为空");
        }
        //回复id不能为空   operation 必须 0 或 1
        //校验登录  (必须登录)
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //校验回复信息是否存在
        //根据回复id查询回复信息
        Query commentId = Query.query(Criteria.where("authorId").is(user.getId()).and("id").is(dto.getCommentRepayId()));
        ApCommentRepay repay = mongoTemplate.findOne(commentId, ApCommentRepay.class);
        if (repay == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "回复消息不存在");
        }
        Map map = new HashMap();
        //2. 如果是点赞  判断是否点过赞
        if (dto.getOperation() == 0) {
            //根据条件
            ApCommentRepayLike repayLike = mongoTemplate.findOne(commentId, ApCommentRepayLike.class);
            if (repayLike != null) {
                //点过赞提示请勿重复点赞
                CustException.cust(AppHttpCodeEnum.DATA_EXIST, "不可以重复点赞");
            }
            //未点过赞， 保存点赞信息
            ApCommentRepayLike apCommentRepayLike = new ApCommentRepayLike();
            apCommentRepayLike.setAuthorId(user.getId());
            apCommentRepayLike.setCommentRepayId(dto.getCommentRepayId());
            apCommentRepayLike.setOperation(dto.getOperation());
            //执行保存
            mongoTemplate.insert(apCommentRepayLike);
            //并将回复信息的点赞数量字段+1
            Update update = new Update();
            Integer likes = repay.getLikes();
            likes += 1;
            update.set("likes", likes).set("updatedTime", new Date());
            //执行修改
            mongoTemplate.updateFirst(commentId, update, ApCommentRepay.class);
            map.put("likes", likes);
        } else {
            //3. 如果是取消赞
            //删除点赞信息
            mongoTemplate.remove(commentId, ApCommentRepay.class);
            //并将回复信息的点赞数量字段-1
            Update update = new Update();
            Integer likes = repay.getLikes();
            likes -= 1;
            update.set("likes", likes).set("updatedTime", new Date());
            //执行修改
            mongoTemplate.updateFirst(commentId, update, ApCommentRepay.class);
            map.put("likes", likes);
        }
        //4. 返回当前回复的最新点赞数量      数据的key:  likes
        return ResponseResult.okResult(map);
    }
}
